#!/usr/bin/env python

__author__ = 'Emiliano Dalla Verde Marcozzi'
__version__ = '0.1'
__copyright__ = 'Licencia GPL v2'

import os, smtplib, mimetypes, time, sys, urllib, urllib2, socket, socket, pdb
import base64, getpass, paramiko

from config import *

from email.MIMEMultipart import MIMEMultipart 
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders


class alertstool:
    """
    """
    # a este lo llaman por si paso algo con un mensaje y lo tira por irc
    # toma parametros del config.py como ser canal, nick , blablabla
    def Irc(self, message):
        """ Send alert by IRC
        """
        network = ALERTS_IRC_SERVER
        port = ALERTS_IRC_PORT
        irc = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
        irc.connect (( network, port ))
        irc.send ( 'NICK %s\r\n' % ALERTS_IRC_NICKNAME ) 
        irc.send ( 'USER SXNet SXNet SXNet :SXNet PyMonitor\r\n' )
        irc.send ( 'JOIN %s\r\n' % ALERTS_IRC_CHANNEL )

        continue_loop = True
        while continue_loop:
            buffer=irc.recv(512)

            for line in buffer.split('\n'):
                #353 is the NAMES response, also send during a JOIN
                if line.count(' ') >1 and line.split()[1] == '353':
                    continue_loop = False
                    break
                    


        irc.send ( 'PRIVMSG %s :%s\r\n' % ( ALERTS_IRC_CHANNEL, message))
        irc.send ( 'PRIVMSG %s :%s\r\n' % ( ALERTS_IRC_CHANNEL, message))
        irc.send ( 'PART %s\r\n' % ALERTS_IRC_CHANNEL) 
        irc.send ( 'QUIT\r\n' )
        irc.close()    

        return


    def Email(self, message, flag, server=None, port=None, user=None, passwd=None, \
                        attachment = None, sender=None, rcpt=None, subject=None):
        """ Send emails. If flag is True, then values are taken from
        config.py, otherwise u must pass all the method parameters.
        Este metodo me parece tiene pocos argumentos ... (?)
        """                                                            

        if flag == True:
            server = ALERTS_EMAIL_SERVER
            port = ALERTS_EMAIL_PORT
            user = ALERTS_EMAIL_USER
            passwd = ALERTS_EMAIL_PASSWD
            rcpt = ALERTS_EMAIL_RCPT
            subject = ALERTS_EMAIL_SUBJECT
            
        text = message  # text / body from email
        
        msg = MIMEMultipart() 
        msg['From'] = user
        msg['To'] = rcpt
        msg['Subject'] = subject
        msg.attach(MIMEText(text))
        
        # If we have something attached ...
        if attachment != None:
            part = MIMEBase('application', "octet-stream")
            part.set_payload( open(attachment,"rb").read() )
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' \
                                                % os.path.basename(attachment))
            msg.attach(part)
        
        mailServer = smtplib.SMTP(server, port)

        # google require this ...
        mailServer.ehlo()

        # try to use TLS
        mailServer.starttls()
        mailServer.ehlo()   # called again, otherwise it doesnt work
                            # mailServer.login authentification.
        
        # try to log in
        mailServer.login(user, passwd)
        
        # try to send the email
        mailServer.sendmail(user, rcpt, msg.as_string())

        mailServer.close()
        

    def SShNotification(self, message, hostname=None, port=None,        \
                        username=None, password=None):
        """ Send notification to some host/s by notify with
        ssh
        """

        # setup logging 
        if hostname or port or username or password is None:
            hostname = ALERTS_HOST_TO_NOTIFY
            port = ALERTS_HOST_TO_NOTIFY_PORT
            username = ALERTS_HOST_TO_NOTIFY_USERNAME
            password = ALERTS_HOST_TO_NOTIFY_PASSWORD
            rfolder = ALERTS_HOST_TO_NOTIFY_REMOTEFOLDER
            rfile = ALERTS_HOST_TO_NOTIFY_REMOTEFOLDER + '/' +      \
                                    ALERTS_HOST_TO_NOTIFY_REMOTEFFILE

        # now, connect and use paramiko Client to negotiate SSH2 across the connection
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname, port, username, password)

        # create .sxnetmonitor dir in the remote machine to write then there
        # the notifies. If the dir exists in the remote machine, stderr
        # will have the error, but nothing shitty more than that happens,
        # so ...

        #stdin, stdout, stderr = client.exec_command('mkdir %s' % rfolder)
        stdin, stdout, stderr = ssh.exec_command('echo "%s" >> %s' %  \
                                                        (message, rfile))
        ssh.close()
